/* ----------------------------------------------------------------------------
* File: map_thread_safe.h
*
* Desc: CMapThreadSafe class for thread-safe maps
*
* Created: 05/03/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#ifndef _MAP_THREAD_SAFE_H_
#define _MAP_THREAD_SAFE_H_

#include <map>
#include "mutex.h"


/************************************************************************/
/*	CMapThreadSafe template class for thread-safed map					*/
/************************************************************************/
template<class T>
class CMapThreadSafe
{
protected:
	typedef std::map<unsigned int, T>	MapInfo;

private:
	// Lock copy constructor and assignment operator
	CMapThreadSafe(const CMapThreadSafe&);
	CMapThreadSafe& operator=(const CMapThreadSafe&);

public:
	CMapThreadSafe() 
	{
		pthread_mutex_init(&m_mutex_access, NULL);
	}

	~CMapThreadSafe()
	{
		typename MapInfo::iterator it = m_map.begin();
		for (; it != m_map.end(); ++it)
			delete it->second;
		m_map.clear();

		pthread_mutex_destroy(&m_mutex_access);
	}

	// Add object
	void Add(T obj)
	{
		CMutexLocker lock(m_mutex_access);
		m_map[m_map.size()] = obj;
	}

	// Remove object
	void Delete(unsigned int id)
	{
		CMutexLocker lock(m_mutex_access);
		typename MapInfo::iterator it = m_map.find(id);
		if (it != m_map.end())
		{
			delete it->second;
			m_map.erase(it);
		}
	}

	// Remove object by iterator
	void Delete(typename MapInfo::iterator it)
	{
		delete it->second;
		m_map.erase(it);
	}

	// Get count elements
	size_t Count()
	{
		CMutexLocker lock(m_mutex_access);
		return m_map.size();
	}

protected:
	pthread_mutex_t m_mutex_access;
	MapInfo m_map;
};

#endif // _MAP_THREAD_SAFE_H_